package com.atguigu.gmall.list.listener;

import com.atguigu.gmall.list.service.ListService;
import com.atguigu.gmall.rabbit.constants.MQConst;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * @Author: lx
 * @Time: 15:34
 * @Description:
 */
@Component
public class Consumer {

    @Autowired
    private ListService listService;

    //接收消息  java代码创建创建队列  交换机 Binging关系
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(name = MQConst.EXCHANGE_DIRECT_GOODS),
            value = @Queue(value = MQConst.QUEUE_GOODS_UPPER,
                    durable = "true",autoDelete = "false" ),
            key = MQConst.ROUTING_GOODS_UPPER
    ))
    public void onSale(Long skuId, Channel channel, Message message) throws Exception{
        try {
            //上架
            listService.onSale(skuId);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            // e.printStackTrace();
            //判断消息是否为重新发送
            if(message.getMessageProperties().isRedelivered()){
                //已经是重发的消息  不让再发了
                //参数1： 消息的标记
                //参数2：是否放回队列   true 表示放回队列  false : 不放回
                channel.basicReject(message.getMessageProperties().getDeliveryTag()
                        ,false);//不入队
            }else{
                //是新的消息   可以重发一次
                //参数1： 消息的标记
                //参数2：是否批量
                //参数3：是否放回队列   true 表示放回队列  false : 不放回
                channel.basicNack(message.getMessageProperties().getDeliveryTag()
                        ,false,true);
            }
        }
    }
}
